<template>
    <d2-container ref="container" type='full'>
        <template slot="header">
            <el-form :inline="true" class='d2-fr'>
                <el-form-item class="d2-mb-0">
                    <el-button type="info" @click="scroll()">
                        回到顶部
                    </el-button>
                </el-form-item>
                <el-form-item class="d2-mb-0">
                    <el-button type="waring" @click="cleanAll()">
                        清空所有
                    </el-button>
                </el-form-item>
                <el-form-item class="d2-mb-0">
                    <el-button type="success" @click='saveBlog()'>发布文章<i class="el-icon-upload el-icon--right"></i>
                    </el-button>
                </el-form-item>

            </el-form>
        </template>

        <h2 class="d2-mt-0">文章标题*</h2>
        <el-input v-model="title" placeholder="请输入内容" class="input-demo-200"></el-input>

        <h2>文章分类*</h2>
        <el-select v-model="blogClass" placeholder="请选择">
            <el-option v-for="item in classLit" :key="item.id" :label="item.className" :value="item.className">
            </el-option>
        </el-select>

        <h2>文章封面/上传附件</h2>
        <el-upload class="avatar-uploader" action="http://dlhtx.zicp.vip:3000/file/upImg" :show-file-list="false"
            style="display:inline;" :on-success="handleAvatarSuccess">
            <img v-if="bgImg" :src="bgImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>

        <el-upload class="upload-demo d2-ml" drag action="http://dlhtx.zicp.vip:3000/file/upload"
            style="display:inline;" :on-success="handleAvatarSuccessFile">
            <i class="el-icon-upload" v-if='!upfile'></i>
            <div class="el-upload__text" v-if='!upfile'>将文件拖到此处，或<em>点击上传(只能上传一个)</em></div>
            <i class="el-icon-s-goods" v-if='upfile' style="color: #67c239;font-size: 46px;margin-top: 50px;"></i>
            <div class="el-upload__text" v-if='upfile'><em>{{upfile.split('-')[1]}}</em></div>
        </el-upload>

        <h2>书写区域*</h2>

        <mavon-editor v-model="markdownValue" :ishljs="true" class="d2-mt" ref='md' @imgAdd="$imgAdd"
            :toolbars='toolbars' />

    </d2-container>
</template>

<script>
import blog from '@/api/blog'
import util from '@/libs/util.js'
export default {
    name: 'newBlog',

    data() {
        return {
            toolbars: {
                bold: true, // 粗体
                italic: true, // 斜体
                header: true, // 标题
                underline: true, // 下划线
                strikethrough: true, // 中划线
                mark: true, // 标记
                superscript: true, // 上角标
                subscript: true, // 下角标
                quote: true, // 引用
                ol: true, // 有序列表
                ul: true, // 无序列表
                link: true, // 链接
                imagelink: true, // 图片链接
                code: true, // code
                table: true, // 表格
                fullscreen: false, // 全屏编辑
                readmodel: false, // 沉浸式阅读
                htmlcode: true, // 展示html源码
                /* 1.3.5 */
                undo: true, // 上一步
                redo: true, // 下一步
                trash: true, // 清空
                save: true, // 保存（触发events中的save事件）
                /* 1.4.2 */
                navigation: true, // 导航目录
                /* 2.1.8 */
                alignleft: true, // 左对齐
                aligncenter: true, // 居中
                alignright: true, // 右对齐
                /* 2.2.1 */
                subfield: true, // 单双栏模式
                preview: true, // 预览
            },
            text: '我是博客编辑',
            title: '',
            blogClass: '',
            classLit: ['分类1'],
            scrollTop: 0,
            containerType: 'full',
            scrollDelay: 10,
            fileList: [],
            bgImg: '',
            upfile: '',
            markdownValue: ''
        }
    },
    mounted() {
        this.findBlogClass()
        this.initData()
        this.autoSave()
        this.setVideoBtn()
    },
    methods: {
        setVideoBtn(){
            setTimeout(res=>{
               console.log()
               let videoBtn = document.createElement("BUTTON");
               let targetElement = document.getElementsByClassName('fa-mavon-picture-o')[0]
               let parent =  document.getElementsByClassName('v-left-item transition')[0]
               videoBtn.setAttribute('aria-hidden',true)
               videoBtn.className='op-icon fa fa-film'
               videoBtn.title='插入视频代码'
               videoBtn.style.margin = '0 0 0 6px'
               videoBtn.addEventListener('click',()=>{
                   if(this.upfile.indexOf('.mp4')!=-1){
                        this.markdownValue += `<video  controls="" poster="http://dlhtx.zicp.vip:3000/img/poster.gif" playsinline="true" preload="none" src="${this.upfile}"></video>`
                   }else{
                       this.$prompt('请输入视频链接', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            }).then(({ value }) => {
                                this.markdownValue += `<video  controls="" poster="http://dlhtx.zicp.vip:3000/img/poster.gif" playsinline="true" preload="none" src="${value}"></video>`
                            }).catch(() => {
                                this.$message({
                                    type: 'info',
                                    message: '取消输入'
                                });       
                        });
                   }
               })
               parent.insertBefore(videoBtn, targetElement.nextSibling);
            },1000)
        },
        cleanAll() {
            this.$confirm('您确认清空所有吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                this.title = ''
                this.blogClass = ''
                this.markdownValue = ''
                this.upFileUrl = ''
                this.bgImg = ''
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        findBlogClass() {
            blog.findBlogClass().then(res => {
                this.classLit = res.data
            }).catch(err => { })
        },
        initData() {
            if (localStorage.getItem('blogSave')) {
                this.$message({ message: '已载入草稿', type: 'success' })
                let blogSave2 = JSON.parse(localStorage.getItem('blogSave'))
                this.title = blogSave2.title
                this.blogClass = blogSave2.blogClass
                this.markdownValue = blogSave2.body
                this.upFileUrl = blogSave2.upFileUrl
                this.bgImg = blogSave2.bgImg
            }
        },
        autoSave() {
            this.interval = setInterval(() => {
                let blogSave = {}
                blogSave.title = this.title //自动保存标题
                blogSave.blogClass = this.blogClass//自动保存分类
                blogSave.body = this.markdownValue
                blogSave.upFileUrl = this.upfile
                blogSave.bgImg = this.bgImg
                localStorage.setItem('blogSave', JSON.stringify(blogSave))//把用户信息存到localStorage
            }, 10000)
        },
        saveBlog() {
            if (this.title == '' || this.markdownValue == '' || this.blogClass == '') return this.$message({ message: '必填内容不可为空!', type: 'warning' })
            this.$confirm('您确认发布该文章吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                blog.saveBlog({ name: util.cookies.get('uuid'), title: this.title, body: this.markdownValue, className: this.blogClass, bgImg: this.bgImg, upFileUrl: this.upfile, isTop: 0, showIndex: 1 })
                    .then(res => {
                        this.$message({
                            message: '保存成功',
                            type: 'success'
                        })
                        //清除数据
                        clearInterval(this.interval)
                        localStorage.removeItem('blogSave')
                        this.title = ''
                        this.markdownValue = ''
                        this.blogClass = ''
                        this.upfile = ''
                        this.bgImg = ''
                        this.$router.replace('/blogList')
                    })
                    .catch(err => { console.log(err) })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        $imgAdd(pos, $file) {
            //上传图片接口
            // console.log($file)
            var formdata = new FormData();
            formdata.append('file', $file);
            blog.upImg(formdata).then(res => {
                if (res.success) {
                    if (!this.bgImg) {
                        this.bgImg = res.data
                        this.$message({ message: '已自动设置为封面', type: 'success' })
                    } else {
                        this.$message({ message: '图片上传成功', type: 'success' })
                    }
                    this.$refs.md.$img2Url(pos, res.data);
                } else {
                    this.$message.error({ message: '上传图片失败' })
                }
            })
        },
        handleAvatarSuccess(res, file) {
            this.bgImg = res.data
        },
        handleAvatarSuccessFile(res, file) {
            this.upfile = res.data
        },
        scroll() {
            this.$refs.container.scrollToTop()
        },
        handleExceed() {

        },
        handlePreview() {

        },
        handleRemove() {

        }
    },
    computed: {
        // 是否开启 better scroll
        betterScroll() {
            return this.$route.query.bs === 'true'
        },
        // 根据滚动位置返回文章的样式
        articleStyle() {
            return {
                opacity: this.scrollTop > 55 ? '1' : '.1'
            }
        }
    }


}
</script>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 245px;

    display: block;
}
</style>
